package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Override
    public ResultInfo login(String username, String password) {
        //根据username查找，如果找不到，返回用户不存在
        Employee employee=employeeMapper.findByUsername(username);
        if (employee==null){
            return ResultInfo.error("用户不存在");
        }
        //比较密码
        String passwordWithMd5 = SecureUtil.md5(password);
        if (!StringUtils.equals(passwordWithMd5,employee.getPassword())){
            return ResultInfo.error("用户密码错误");
        }
        //查看用户状态
        if (employee.getStatus()==Employee.STATUS_DISABLE){
            return ResultInfo.error("当前处于禁用状态，禁止登录");
        }
        return ResultInfo.success(employee);
    }

    @Override
    public List<Employee> findByName(String name) {
        return employeeMapper.findByName(name);
    }
    //添加员工
    @Override
    public void save(Employee employee) {
        //补齐参数
        employee.setId(IdUtil.getSnowflake(1,1).nextId());
        employee.setPassword(SecureUtil.md5("123"));
        employee.setStatus(Employee.STATUS_ENABLE);
        //时间
//        employee.setCreateTime(new Date());
//        employee.setUpdateTime(new Date());
        //操作人
//        employee.setCreateUser(1L);
//        employee.setUpdateUser(1L);
        //调用mapper
        employeeMapper.save(employee);
    }

    @Override
    public Employee findById(Long id) {
        return employeeMapper.findById(id);
    }

    @Override
    public void update(Employee employee) {
        //重新赋值参数
//        employee.setUpdateUser(1L);
//        employee.setUpdateTime(new Date());
        employeeMapper.update(employee);
    }
}
